package fallon;

import com.adxon.MsgException;
import com.adxon.data.Figure;
import com.adxon.data.Ratee;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;

import java.io.IOException;
import java.io.InputStream;

public class Collection extends Ratee{
	protected static String BSK="i206";

	public static Collection create(String key,String type)throws MsgException{
		Collection r=new Collection();
		r.setPermaLink(key);
		r.typ=type;
		r.update();
		return r;
	}
	public static PreparedQuery query(Collection template){
		Filter f=null;
		if(template.ow!=0){
			f=new FilterPredicate("ow",FilterOperator.EQUAL,template.ow);
		}
		if(template.rt!=0)
			f=f==null?new FilterPredicate("rt",FilterOperator.EQUAL,template.rt):
				CompositeFilterOperator.and(f,
					new FilterPredicate("rt",FilterOperator.EQUAL,template.rt));
		Query q=new Query(BSK);
		if(f!=null)
			q.setFilter(f);
		q.addSort("tc",SortDirection.DESCENDING);
		return DatastoreServiceFactory.getDatastoreService().prepare(q);
	}
	public static void refresh(long owner){
		String p=owner+"/";
		PreparedQuery r=Candidate.query(20);
		try{
			for(Entity t:r.asIterable()){
				Candidate a=new Candidate();
				a.update(t);
				Collection c=new Collection();
				c.setPermaLink(p+a.getPermaLink());
				c.update();
				c.setId(a);
				c.setOwner(owner);
				c.setRate(13);
				c.commit();
			}
		}catch (MsgException e){
			e.printStackTrace();
		}
	}

	protected Figure att;		// attachment bits
	protected String typ;	// type of attachment bits to get

	public Collection(){
		super();
		bsk=BSK;
	}
	protected String allocateId()throws MsgException{
		if(att!=null){
			att.setOwner(ow);
			att.setRate(rt);
			att.commit();
		}
		id=att.getId();
		return ow+"/"+id;
	}
	public byte[] getBits()throws MsgException{
		prepAtt();
		att.setPermaLink(id);
		att.update();
		return att.getBits(typ);
	}
	public String getContentType(){
		return "image";
	}
	private void prepAtt(){
		if(att==null)
			att=new Figure();
	}
	public void setBits(InputStream stream)throws IOException{
		prepAtt();
		att.setBits(stream);
	}
	public void setContentType(String type){
		prepAtt();
		att.setContentType(type);
	}
	public void setMaxSize(String size){
		prepAtt();
		att.setMaxSize(size);
	}
	public void setRatio(String ratio){
		prepAtt();
		att.setRatio(ratio);
	}
}